//
//  YYLTextView.swift
//  XinlangWeibo
//
//  Created by yangyinglei on 2017/4/6.
//  Copyright © 2017年 yangyinglei. All rights reserved.
//

import UIKit

class YYLTextView: UITextView {
    
    //懒加载控件 为了以后可移植使用 这里控件用原生的
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.text = "请在这里输入微博内容请在这里输入微博内容请在这里输入微博内容请在这里输入微博内容请在这里输入微博内容"
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = UIColor.lightGray
        label.numberOfLines = 0
        label.sizeToFit()
        
        return label
    }()
    
    //设置站位的文字
    var placeHolder: String?{
        didSet{
        placeholderLabel.text = placeHolder
        }
    }
    //设置站位文字的大小
    override var font: UIFont? {
        didSet{
            if font != nil {
                placeholderLabel.font = font
            }
        }
    }
    //根据是否有文字判断站位文字的显示和隐藏  只有从控制器设置文字的时候才会走set方法  手动输入不会走这个方法的
    override var text: String? {
        didSet {
        
        placeholderLabel.isHidden = self.hasText
        }
    }
    
    //MARK:---------------------------------------------------------------------------

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        backgroundColor = UIColor.white
        
        NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: .UITextViewTextDidChange, object: nil)
    
        addSubview(placeholderLabel)
        
        //布局 用原始布局
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 7))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
        
    }
    
    @objc private func textChange() {
    
    placeholderLabel.isHidden = self.hasText
    }
    //移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
